package com.canomo.base.controller;

import com.canomo.base.entity.FileInfo;
import com.canomo.base.service.FileInfoService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

/**
 * 文件上传
 */
@Controller
@RequestMapping("fileupload")
public class FileUploadController {

    @Autowired
    private FileInfoService fileInfoService;

    @RequestMapping("upload")
    @ResponseBody
    public Long upload(HttpServletRequest request) {
        Long fileId = null;
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            Iterator iter=multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    fileId = fileInfoService.save(file);
                    break;
                }
            }
        }
        return fileId;
    }

    @RequestMapping("{id}")
    public String getFile(@PathVariable("id") String id,HttpServletResponse response) {

        FileInfo fileInfo = fileInfoService.selectById(id);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(fileInfo.getFilePath()));
            IOUtils.copy(inputStream,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;


    }
}
